from django.contrib.auth import login, authenticate
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.forms import UserCreationForm
import json
from django.contrib.auth import logout

import logging
# 获取一个 logger 实例
logger = logging.getLogger(__name__)

@csrf_exempt
def register(request):
    if request.method == 'POST':
        # 从 request.POST 中获取前端发送的数据
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username')
        password = data.get('password')
        confirm_password = data.get('confirmPassword')

        # 创建用户注册表单并验证数据
        form = UserCreationForm({'username': username, 'password1': password, 'password2': confirm_password})
        if form.is_valid():
            # 保存用户
            user = form.save()
            # 登录用户
            login(request, user)
            return JsonResponse({'success': True, 'message': 'Registration successful'})
        else:
            # 返回表单验证错误信息
            errors = dict(form.errors.items())
            print(errors)
            return JsonResponse({'success': False, 'errors': errors})
    else:
        # 如果请求方法不是 POST，返回一个 JSON 欢迎信息
        return JsonResponse({'message': 'Welcome to the registration page!'})

@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        # 从 request.POST 中获取前端发送的数据
        username = data.get('username')
        password = data.get('password')

        # 使用 Django 提供的 authenticate() 函数验证用户凭据
        user = authenticate(request, username=username, password=password)
        if user is not None:
            # 如果认证成功，登录用户
            login(request, user)
            return JsonResponse({'success': True, 'message': 'Login successful'})
        else:
            # 如果认证失败，返回错误消息
            return JsonResponse({'success': False, 'message': 'Invalid credentials'})
    else:
        # 如果请求方法不是 POST，返回一个 JSON 欢迎信息
        return JsonResponse({'message': 'Welcome to the login page!'})


@csrf_exempt
def user_logout(request):
    if request.method == 'POST':
        logout(request)
        return JsonResponse({'success': True, 'message': 'Logout successful'})
    return JsonResponse({'message': 'Only POST method is allowed'}, status=405)
